package com.snsoft.kpoptop10;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.*;

import net.daum.adam.publisher.AdView;
import net.daum.adam.publisher.AdView.OnAdClickedListener;
import net.daum.adam.publisher.AdView.OnAdClosedListener;
import net.daum.adam.publisher.AdView.OnAdFailedListener;
import net.daum.adam.publisher.AdView.OnAdLoadedListener;
import net.daum.adam.publisher.AdView.OnAdWillLoadListener;
import net.daum.adam.publisher.impl.AdError;
import net.daum.adam.publisher.AdView.AnimationType;

public class KPOPTOP10Activity extends Activity {
	
	public WebView wv;
	public Dialog dialog;
	private String wvurl = "";

    private com.google.ads.AdView admobView = null;
	private net.daum.adam.publisher.AdView adamView = null;
	private static final String LOGTAG = "Adam";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Activity activity = this; 
        
        setContentView(R.layout.main);
        
        wv = (WebView)findViewById(R.id.webview);
        
        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setLoadsImagesAutomatically(true);
        wv.getSettings().setLightTouchEnabled(true);
        wv.getSettings().setPluginsEnabled(true);
        //wv.setVerticalScrollBarEnabled(false);
        wv.setHorizontalScrollBarEnabled(false);
        wv.setVerticalScrollbarOverlay(true);

        wv.setBackgroundColor(Color.BLACK);
        
        // Loading dialog set
        dialog = new Dialog(this, R.style.SNDialog);
        dialog.addContentView(new ProgressBar(this), new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        
        wv.setWebViewClient(new WebViewClient()
        {
        	// Webview handler
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url)
        	{
        		if(url.startsWith("http://www.youtube.com"))
        		{
        			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        			intent.addCategory(Intent.CATEGORY_BROWSABLE);
        			intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
        			startActivity(intent);
        		}
        		else
        			view.loadUrl(url);

        		return true;
        	}
        	
        	
        	@Override     
        	public void onPageStarted(WebView view, String url, Bitmap favicon) 
        	{
        		dialog.show();
        	} 
        	
        	@Override     
        	public void onPageFinished(WebView view, String url) 
        	{
        		wvurl = wv.getUrl();
        		
        		if(dialog.isShowing())
        		{
        			dialog.dismiss();
        		}
        	}      
        	
        	@Override
        	public void onReceivedError(WebView view, int errorCode,String description, String failingUrl)
        	{
        		wv.loadData("<html><body align='center' valign='center'></body></html>", "text/html", "UTF-8");
        		Toast.makeText(activity, "Network unavailable. Please try again later.", Toast.LENGTH_LONG).show();
        	}
        });
        
        wv.loadUrl("file:///android_asset/index.html");
        
        // adam 실행
        initAdam();
        
        // Admob Setting
        admobView = (com.google.ads.AdView)this.findViewById(R.id.admobView);
        AdRequest adRequest = new AdRequest();
        admobView.loadAd(adRequest);
        
        admobView.setAdListener(new AdListener() 
        {
        	public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) 
        	{
			}

			public void onDismissScreen(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onLeaveApplication(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onPresentScreen(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onReceiveAd(Ad arg0) {
				// TODO Auto-generated method stub
			}

        });
    }

    private void initAdam() 
    {
		// Ad@m sdk 초기화 시작
    	adamView = (AdView) findViewById(R.id.adamView);

		// 광고 클릭시 실행할 리스너
    	adamView.setOnAdClickedListener(new OnAdClickedListener() {
			public void OnAdClicked() {
				Log.i(LOGTAG, "광고를 클릭했습니다.");
			}
		});

		// 광고 내려받기 실패했을 경우에 실행할 리스너
    	adamView.setOnAdFailedListener(new OnAdFailedListener() {
			public void OnAdFailed(AdError arg0, String arg1) {
				Log.w(LOGTAG, arg1);
				
				admobView.setVisibility(View.VISIBLE);			// 애드몹 표시
				admobView.bringToFront();						// 애드몹 상위
			}
		});

		// 광고를 정상적으로 내려받았을 경우에 실행할 리스너
    	adamView.setOnAdLoadedListener(new OnAdLoadedListener() {
			public void OnAdLoaded() {
				Log.i(LOGTAG, "광고가 정상적으로 로딩되었습니다.");
				
				admobView.setVisibility(View.INVISIBLE);		// 애드몹 숨김
				adamView.bringToFront();						// 아담 상위
				
				
			}
		});

		// 광고를 불러올때 실행할 리스너
    	adamView.setOnAdWillLoadListener(new OnAdWillLoadListener() {
			public void OnAdWillLoad(String arg1) {
				Log.i(LOGTAG, "광고를 불러옵니다. : " + arg1);
			}
		});

		// 광고를 닫았을때 실행할 리스너
    	adamView.setOnAdClosedListener(new OnAdClosedListener() {
			public void OnAdClosed() {
				Log.i(LOGTAG, "광고를 닫았습니다.");
			}
		});

		// 할당 받은 clientId 설정
    	adamView.setClientId("2c52Z3NT137786ab8f1");
    	
    	adamView.setRequestInterval(12);

		// Animation 효과 : 기본 값은 AnimationType.NONE
    	adamView.setAnimationType(AnimationType.FLIP_HORIZONTAL);

    	adamView.setVisibility(View.VISIBLE);
	}
    
    // Back key setting
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
    	if(keyCode == KeyEvent.KEYCODE_BACK)
    	{
    		if(wvurl.matches(".*sub.*") && wv.canGoBack())
        	{
    			wv.goBack();
        		return true;
        	}
    		else
    		{
    			new AlertDialog.Builder(this)
    			.setMessage("Are you sure you want to quit?")
    			.setPositiveButton("Yes", new DialogInterface.OnClickListener()
    			{
					
					public void onClick(DialogInterface dialog, int which) 
					{
						finish();
					}
				})
				.setNegativeButton("No", null).show();
	    		return true;
    		}
    	}
    	return super.onKeyDown(keyCode, event);
    }


    
    // Screen rotating fix
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
    	super.onConfigurationChanged(newConfig);
    }
    
    @Override
	public void onDestroy() {
		super.onDestroy();

		if (admobView != null) 
		{
			admobView.destroy();
			admobView = null;
		}
		
		if (adamView != null) 
		{
			adamView.destroy();
			adamView = null;
		}
	}
}